package com.yueyang.sojourn.server.controller;

import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.vo.UploadResult;
import com.yueyang.sojourn.server.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

/**
 * @author yemingxing
 * @summary
 * @Copyright (c) 2020, Yueyang Group All Rights Reserved.
 * @since 2020-02-19
 */
@RestController
@Slf4j
@Api(tags = "文件服务器 API")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    @ApiImplicitParam(name = "X-Token", paramType = "header", required = true)
    @ApiOperation(value = "获取文件上传凭证", notes = "上传凭证, 一小时内有效")
    @GetMapping("/upToken")
    public String getToken(@RequestParam String accessKey,
                           @RequestParam String secretKey,
                           @RequestParam String bucket,
                           @ApiParam("文件名。如果是覆盖上传，则传需要覆盖的文件名") @RequestParam(required = false) String fileName) {
        return fileService.getUpToken(accessKey, secretKey, bucket, fileName);
    }

    @ApiImplicitParam(name = "X-Token", paramType = "header", required = true)
    @ApiOperation(value = "上传文件（不带上传凭证）")
    @PostMapping("/sojourn/upload")
    public UploadResult upload(@RequestParam String accessKey,
                       @RequestParam String secretKey,
                       @RequestParam String bucket,
                       @RequestParam MultipartFile file,
                       @ApiParam("文件名。如果是覆盖上传，则传需要覆盖的文件名") @RequestParam(required = false) String fileName) {
        try {
            return fileService.upload(super.getLoginUserId(), accessKey, secretKey, bucket, file.getBytes(), fileName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            JAssert.justFailed("文件上传失败，请联系管理员或稍后重试");
            return null;
        }
    }

    @ApiImplicitParam(name = "X-Token", paramType = "header", required = true)
    @ApiOperation(value = "上传文件（带上传凭证）")
    @PostMapping("/sojourn/uploadWithToken")
    public UploadResult upload(@RequestHeader String upToken,
                               @RequestParam MultipartFile file,
                               @ApiParam("文件名。如果是覆盖上传，则传需要覆盖的文件名，且与upToken获取方式需一致") @RequestParam(required = false) String fileName) {
        try {
            return fileService.upload(super.getLoginUserId(), upToken, file.getBytes(), fileName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            JAssert.justFailed("文件上传失败，请联系管理员或稍后重试");
            return null;
        }
    }


}
